package com.wu.framework.http;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @description: 分页参数数据获取类
 */
public class PageMethodArgumentResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (!methodParameter.hasParameterAnnotation(RequestPage.class)) {
            return false;
        }
        Class clazz = methodParameter.getParameterType();
        return PageBO.class.isAssignableFrom(clazz) || Page.class.isAssignableFrom(clazz);
    }

    @Nullable
    @Override
    public Object resolveArgument(
            MethodParameter methodParameter,
            @Nullable ModelAndViewContainer modelAndViewContainer,
            NativeWebRequest nativeWebRequest,
            @Nullable WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Integer current =
                Optional.ofNullable(request.getParameter("current"))
                        .map(Integer::valueOf)
                        .orElse(1);
        Integer size =
                Optional.ofNullable(request.getParameter("size"))
                        .map(Integer::valueOf)
                        .orElse(10);
        PageBO pageBO = new PageBO(current, size);
        if (PageBO.class.isAssignableFrom(methodParameter.getParameterType())) {
            return pageBO;
        }else {
            return pageBO.convert2Page();
        }
    }
}
